" vim: ft=vim
" Test setattr()

Execute(Set attribute with a Dict);
let bar = {}
call object#setattr(bar, 'weight', 10)
AssertEqual bar.weight, 10
call object#setattr(bar, 'weight', 'heavy')
AssertEqual bar.weight, 'heavy'


Execute(Throw WrongType when obj is not a Dict or name is not a String);
let wrong_types = [[ 'str', 'attr'], [ {}, 1 ], [ 'str', 1 ]]

for [obj, name] in wrong_types
  AssertThrows call object#setattr(g:obj, g:name, 1)
  Assert g:vader_exception =~# 'WrongType'
endfor


Execute(Hook into __setattr__());
let cls = { 'speed' : 100, 'duration' : 10 }
function! cls.__setattr__(name, val)
  if a:name is# 'speed'
    throw 'speed is readonly'
  endif
  if a:name is# 'duration' && a:val >= 0
    " Only accept positive duration
    let self.duration = a:val
  endif
endfunction

AssertThrows call object#setattr(g:cls, 'speed', 20)
Assert g:vader_exception is# 'speed is readonly'

call object#setattr(cls, 'duration', -1)
AssertEqual cls.duration, 10

call object#setattr(cls, 'duration', 20)
AssertEqual cls.duration, 20
